/*
 * @Author: your name
 * @Date: 2021-06-24 11:20:44
 * @LastEditTime: 2021-06-24 11:26:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /shujucaiji/lib/handler/record.js
 */
const md5 = require('md5');
const superagent = require('superagent');
const { Record, Orientation} = require('../db');
const {HOST, CONSTNTSTR, INDEX} = require('../../config');
const {dateFormat } = require('../utils/index');

const inner = () => {};
const outer = () => {};

// 获取token值
inner.getAccessToken = () => {
  const date = dateFormat(new Date(), 'Y-m-d').replace(/-/g, '');
  const token = md5(`${CONSTNTSTR}${date}`);
  return token;
};


// 数据请求代理接口
outer.getRemoteData = async() => {
  const token = inner.getAccessToken();
  const url = `${HOST}?index=${INDEX}&token=${token}`;
  const res = await superagent.post(url);
  return JSON.parse(res.text);
};


// 上传保存数据
outer.recevieData = async (data) => {
  const { projectId, workName} = data;
  if(!projectId || !workName) return;
  const doc = new Record(data);
  doc.save();
};

// 保存导向数据
outer.recordOrientationData = async(options) => {
  const { data } = options;
  try {
    const { projectId } = data[0];
    await Orientation.deleteMany({ projectId });
    await Orientation.insertMany(data);
    return { success: true, msg: '导向数据导入成功'};
  } catch (error) {
    return { success: false, msg: '数据导入失败', data: error };
  }
};

// 查询导向数据
outer.getTrackData = async(options) => {
  const { projectId } = options;
  try {
    const data = await Orientation.find({ projectId }, { 'MD': 1, 'Elev': 1, 'Right': 1 }).sort({ Away: 1});
    if(data.length < 1) {
      return { 'success': false, msg: '暂无导向数据'};
    }
    return { 'success': true,msg: '查询成功', data };
  } catch (error) {
    return { 'success': false, msg: '暂无导向数据'};
  }
};


module.exports = outer;
